﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: CrMosk
 * Дата: 10.05.2013
 * Время: 13:02
 *  
 */
using System;
using System.IO;
namespace Region.Utils
{
  /// <summary>
  /// Класс CRCStream является стандартным потоком вычисляет CRC32 хеш для всех записаных данных
  /// </summary>
  class CRC32Stream : Stream
  {
    UInt32[] CRC_Table;
    UInt32 m_CRC;
    public UInt32 CRC { get { return m_CRC ^ 0xFFFFFFFF; } }
    public void Restart() { m_CRC = 0xFFFFFFFF; }
    public CRC32Stream()
    {
        CRC_Table = new UInt32[256];
        for (UInt32 i = 0; i < 256; i++)
        {
            UInt32 CRCT = i;
            for (Int32 j = 0; j < 8; j++) CRCT = ((CRCT & 0x00000001) == 0x00000001) ? ((CRCT >> 1) ^ 0xEDB88320) : (CRCT >> 1);
            CRC_Table[i] = CRCT;
        }
        m_CRC = 0xFFFFFFFF;
    }
    public override bool CanRead{get { return false; }}
    public override bool CanSeek{get { return false; }}
    public override bool CanWrite{get { return true; }}
    public override void Flush(){throw new NotImplementedException();}
    public override long Length{get { throw new NotImplementedException(); }}
    public override long Position{get{throw new NotImplementedException();}set{throw new NotImplementedException();}}
    public override int Read(byte[] buffer, int offset, int count){throw new NotImplementedException();}
    public override long Seek(long offset, SeekOrigin origin){throw new NotImplementedException();}
    public override void SetLength(long value){throw new NotImplementedException();}
    public override void Write(byte[] buffer, int offset, int count)
    {
        Int32 S = offset + count;
        for (Int32 i = offset; i < S; i++)
            m_CRC = CRC_Table[(m_CRC ^ buffer[i]) & 0xFF] ^ (m_CRC >> 8);
        return;
    }
  }
}
